/**
 * @param {string[]} words
 * @param {string} chars
 * @return {number}
 */
var countCharacters = function (words, chars) {
    let charMap = new Map()
    let ans = 0
    for (let char of chars) {
        charMap.set(char, (charMap.has(char) ? charMap.get(char) + 1 : 1))
    }
    for (let word of words) {
        let wordMap = new Map()
        for (let char of word) {
            wordMap.set(char, (wordMap.has(char) ? wordMap.get(char) + 1 : 1))
        }
        let enough = true
        for (let char of wordMap) {
            if (wordMap.get(char) > charMap.get(char) || charMap.get(char) === undefined) {
                enough = false
                break

            }
        }
        if (enough) {
            ans += word.length
        }
    }
    return ans

};

words=["cat","bt","hat","tree"]
chars="atach"

console.log(countCharacters(words,chars))
